import cv2 as cv
import numpy as np
img1 = cv.imread('D:\photo\I7 PLUS\Books\Book_01.jpg')
img2 = cv.imread('D:\photo\I7 PLUS\Books\Book_02.jpg')
img1 = cv.resize(img1,None,fx=0.4,fy=0.4)
img2 = cv.resize(img2,None,fx=0.4,fy=0.4)
orb = cv.ORB_create()
kp1 = orb.detect(img1,None)
kp2 = orb.detect(img2,None)
kp1,des1 = orb.compute(img1,kp1)
kp2,des2 = orb.compute(img2,kp2)

bf = cv.BFMatcher(cv.NORM_L1)
matches = bf.knnMatch(des1,des2,2)

match_1 = cv.drawMatchesKnn(img1,kp1,img2,kp2,matches,None,(255,255,0),(0,255,255),flags=2)
cv.imshow('img_matches',match_1)
cv.waitKey()

#匹配
good = []
pt1 = []
pt2 = []
for (m,n) in matches:
    if m.distance < 0.8*n.distance:
        good.append([m])
        pt1.append(kp1[m.queryIdx].pt)
        pt2.append(kp2[m.trainIdx].pt)
pt1 = np.int32(pt1)
pt2 = np.int32(pt2)
match_2 = cv.drawMatchesKnn(img1,kp1,img2,kp2,good,None,(255,255,0),(0,255,255),flags=2)
print(good)
cv.imshow('img_matches',match_2)
cv.waitKey()

#ORB+RANSAC
M,mask = cv.findHomography(pt1,pt2,method=cv.RANSAC,ransacReprojThreshold=5,confidence=0.9)
print(mask.shape)
match_3 = cv.drawMatchesKnn(img1,kp1,img2,kp2,good,None,(255,255,0),(0,255,255),matchesMask=mask,flags=2)
cv.imshow('img_matches',match_3)
cv.waitKey()